package com.cditie.jfinaltask.common.jcrontab;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Vector;

import org.jcrontab.Crontab;
import org.jcrontab.data.CrontabEntryBean;
import org.jcrontab.data.CrontabEntryException;
import org.jcrontab.data.CrontabParser;
import org.jcrontab.data.DataNotFoundException;
import org.jcrontab.data.DataSource;
import org.jcrontab.data.FileSource;

public class ClassPathFileSource  extends FileSource{
	

	 public ClassPathFileSource()
	    {
	        cp = new CrontabParser();
	        cachedBeans = null;
	        crontab_file = "crontab";
	        if(Crontab.getInstance().getProperty("org.jcrontab.data.file") == null)
	            Crontab.getInstance().setProperty("org.jcrontab.data.file", crontab_file);
	    }

	    public synchronized DataSource getInstance()
	    {
	        if(instance == null)
	            instance = new ClassPathFileSource();
	        return instance;
	    }

	    public synchronized CrontabEntryBean find(CrontabEntryBean ceb)
	        throws CrontabEntryException, IOException, DataNotFoundException
	    {
	        CrontabEntryBean cebra[] = findAll();
	        for(int i = 0; i < cebra.length; i++)
	            if(cebra[i].equals(ceb))
	                return cebra[i];

	        throw new DataNotFoundException((new StringBuilder()).append("Unable to find :").append(ceb).toString());
	    }

	    protected InputStream createCrontabStream(String name)
	        throws IOException
	    {
			return new FileInputStream( HRLoadCrontabServlet.class.getClassLoader().getResource(name).getPath());
	    }

	    public synchronized CrontabEntryBean[] findAll()
	        throws CrontabEntryException, IOException, DataNotFoundException
	    {
	        boolean bSeconds[] = new boolean[60];
	        boolean bYears[] = new boolean[10];
	        Vector listOfLines = new Vector();
	        Vector listOfBeans = new Vector();
	        String filename = Crontab.getInstance().getProperty("org.jcrontab.data.file");
	        InputStream fis = createCrontabStream(filename);
	        BufferedReader input = new BufferedReader(new InputStreamReader(fis));
	        String strLine;
	        while((strLine = input.readLine()) != null) 
	        {
	            strLine = strLine.trim();
	            listOfLines.add(strLine);
	        }
	        input.close();
	        if(listOfLines.size() > 0)
	        {
	            for(int i = 0; i < listOfLines.size(); i++)
	            {
	                String strLines = (String)listOfLines.get(i);
	                if(!strLines.equals("") && strLines.charAt(0) != '#')
	                {
	                    CrontabEntryBean entry = cp.marshall(strLines);
	                    listOfBeans.add(entry);
	                }
	            }

	        } else
	        {
	            throw new DataNotFoundException("No CrontabEntries available");
	        }
	        int sizeOfBeans = listOfBeans.size();
	        if(sizeOfBeans == 0)
	            throw new DataNotFoundException("No CrontabEntries available");
	        CrontabEntryBean finalBeans[] = new CrontabEntryBean[sizeOfBeans];
	        for(int i = 0; i < sizeOfBeans; i++)
	        {
	            finalBeans[i] = (CrontabEntryBean)listOfBeans.get(i);
	            finalBeans[i].setId(i);
	        }

	        cachedBeans = finalBeans;
	        return cachedBeans;
	    }

	    public synchronized void remove(CrontabEntryBean ceb[])
	        throws Exception
	    {
	        CrontabEntryBean thelist[] = findAll();
	        CrontabEntryBean result[] = new CrontabEntryBean[thelist.length - ceb.length];
	        for(int i = 0; i < thelist.length; i++)
	        {
	            if(thelist[i] != null)
	                thelist[i].setId(-1);
	            for(int y = 0; y < ceb.length; y++)
	            {
	                ceb[y].setId(-1);
	                if(thelist[i] != null && thelist[i].equals(ceb[y]))
	                    thelist[i] = null;
	            }

	        }

	        int resultCounter = 0;
	        for(int i = 0; i < thelist.length; i++)
	            if(thelist[i] != null)
	            {
	                result[resultCounter] = thelist[i];
	                resultCounter++;
	            }

	        storeAll(result);
	    }

	    public synchronized void storeAll(CrontabEntryBean list[])
	        throws CrontabEntryException, FileNotFoundException, IOException
	    {
	        File fl = new File(Crontab.getInstance().getProperty("org.jcrontab.data.file"));
	        PrintStream out = new PrintStream(new FileOutputStream(fl));
	        for(int i = 0; i < list.length; i++)
	            if(list[i] != null)
	            {
	                out.println("#");
	                out.println(cp.unmarshall(list[i]));
	            }

	        out.println("#");
	    }

	    public synchronized void store(CrontabEntryBean beans[])
	        throws CrontabEntryException, IOException, DataNotFoundException
	    {
	        CrontabEntryBean thelist[] = null;
	        boolean succedded = false;
	        try
	        {
	            thelist = findAll();
	            succedded = true;
	        }
	        catch(Exception e)
	        {
	            if(e instanceof DataNotFoundException)
	                storeAll(beans);
	            else
	                throw new DataNotFoundException("Unable to find CrontabEntries");
	        }
	        if(succedded)
	        {
	            int size = thelist.length + 1;
	            CrontabEntryBean resultlist[] = new CrontabEntryBean[size];
	            Vector ve = new Vector();
	            for(int i = 0; i < thelist.length; i++)
	                ve.add(thelist[i]);

	            for(int i = 0; i < beans.length; i++)
	                ve.add(beans[i]);

	            for(int i = 0; i < ve.size(); i++)
	                resultlist[i] = (CrontabEntryBean)ve.get(i);

	            storeAll(resultlist);
	        }
	    }

	    private CrontabParser cp;
	    private static ClassPathFileSource instance;
	    private CrontabEntryBean cachedBeans[];
	    protected long lastModified;
	    private String crontab_file;
}
